var express = require('express');
var router = express.Router();
var smartUtil = require('./ccServer');
let utils = require('./../../utils/utils');
var MongoDB = require('../../database/mongodb');
const BizResult = require("../../service/BizResult");
const { v4: uuidv4 } = require('uuid');
var encryptUtil = require('../../utils/encryptUtil');

router.post('/loginByToken', function(req, res, next) {
  smartUtil.getContextByToken(req.body.accessToken).then((loginName) => {
    let conditions = {
      '$or': [
        { loginName: loginName },
        { email: loginName }
      ]
    }
    MongoDB.findOne('users', conditions, (err, docs) => {
      if (err) {
        next(new Error('单点登录失败，找不到用户'))
      } else {
        res.cookie("user", docs, { maxAge: 1000 * 60 * 30, sameSite: false });
        docs.token = uuidv4();
        res.json(docs);
      }
    });
  }).catch((code) => {
    next(new Error('单点登录失败，请输入账号密码登录'))
  })
});

router.post('/login', function(req, res, next) {
  ewLogin(req, res, next).then((data) => {
    saveOrUpdateUser(data, req).then((docs) => {
      let data = JSON.parse(JSON.stringify(docs))
      data.token = uuidv4();
      res.cookie("user", data, { maxAge: 1000 * 60 * 30, sameSite: false });
      res.json(BizResult.success(data))
    })
  }).catch((code) => {
    if (code == 0) {
      next(new Error('用户已停用'))
    } else {
      ccLogin(req).then((ccUser) => {
        newUserLogin(ccUser, req, res, next)
      }).catch((err) => {
        console.log('error:' + err)
        next(err);
      });
    }
  })
});

/**
 * 获取用户有权限的菜单.
 */
router.get('/getMenuList', function(req, res, next) {
  let loginUser = req.cookies['user']
  let condition = {
    userId: loginUser._id
  }
  MongoDB.find('userRoles', condition, null, null, function (err, roles) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      let roleIds = new Set()
      for (let index = 0; index < roles.length; index++) {
        const element = roles[index];
        roleIds.add(element.roleId)
      }
      let condition = {
        roleId: { '$in': [...roleIds] },
        authType: "MENU"
      }
      MongoDB.find('roleAuth', condition, null, null, function (err, authList) {
        let menuIds = new Set()
        for (let index = 0; index < authList.length; index++) {
          const element = authList[index];
          menuIds.add(element.businessId)
        }
        let condition = {
          "$or": [
            { _id: { '$in': [...menuIds] } },
            { public: "1" }
          ]
        }
        MongoDB.find('menus', condition, null, { sort: 1 }, function (err, menuList) {
          if (err) {
            res.status(500).send("查询失败");
          } else {
            res.json(BizResult.success(utils.arrayToTree(menuList)));
          }
        })
      });
    }
  });
})

/**
 * 获取用户有权限的菜单功能.
 */
router.get('/getMenuButtonList', function(req, res, next) {
  let loginUser = req.cookies['user']
  let condition = {
    userId: loginUser._id
  }
  MongoDB.find('userRoles', condition, null, null, function (err, roles) {
    if (err) {
      res.status(500).send("查询失败");
    } else {
      let roleIds = new Set()
      for (let index = 0; index < roles.length; index++) {
        const element = roles[index];
        roleIds.add(element.roleId)
      }
      let condition = {
        roleId: { '$in': [...roleIds] },
        authType: "BUTTON"
      }
      MongoDB.find('roleAuth', condition, null, null, function (err, authList) {
        let buttonIds = new Set()
        for (let index = 0; index < authList.length; index++) {
          const element = authList[index];
          buttonIds.add(element.businessId)
        }
        let condition = {
          _id: { '$in': [...buttonIds] }
        }
        MongoDB.find('menuButtons', condition, null, null, function (err, menuButtonList) {
          if (err) {
            res.status(500).send("查询失败");
          } else {
            res.json(BizResult.success(menuButtonList));
          }
        })
      });
    }
  });
})

function newUserLogin(ccUser, req, res, next) {
  let conditions = {
    loginName: ccUser.loginName
  }
  MongoDB.findOne('users', conditions, (err, docs) => {
    if(!err && docs){
      let data = JSON.parse(JSON.stringify(docs))
      data.password = getParamter(req, 'password')
      data.accessToken = ccUser.accessToken
      data.userPicId = ccUser.userPicId
      res.cookie("user", data, { maxAge: 1000 * 60 * 30, sameSite: false });
      saveOrUpdateUser(data, req).then((docs) => {
        let data = JSON.parse(JSON.stringify(docs))
        data.access_token = uuidv4();
        res.cookie("user", data, { maxAge: 1000 * 60 * 30, sameSite: false });
        res.json(BizResult.success(data))
      })
    } else {
      let newUser = {
        userName: encryptUtil.sm4Decrypt(ccUser.userName),
        password: getParamter(req, 'password'),
        email: encryptUtil.sm4Decrypt(ccUser.email),
        loginName: ccUser.loginName,
        sex: ccUser.sex === 0 ? "male" : "female",
        state: 1
      }
      console.log('保存新用户')
      saveOrUpdateUser(newUser, req).then(docs => {
        let data = JSON.parse(JSON.stringify(docs))
        data.accessToken = ccUser.accessToken
        data.access_token = uuidv4();
        res.cookie("user", data, { maxAge: 1000 * 60 * 30, sameSite: false });
        res.json(BizResult.success(data))
      })
    }
  });
}

router.get('/logout', function(req, res, next){
  res.clearCookie("user");
  res.json(BizResult.success("退出成功"))
});

router.get('/user', (req, res) => {
  res.status(200).send("pong!");
});

router.get('/ping', (req, res) => {
  res.status(200).send("pong!");
});

/**
 * 当前系统登录.
 */
function ewLogin(req, res, next){
  console.log('ewlogin');
  let loginName = getParamter(req, 'loginName');
  let password = getParamter(req, 'password');
  let conditions = {
    '$or': [
      { loginName: loginName },
      { email: loginName }
    ]
  }
  return new Promise((resolve, reject) => {
    MongoDB.findOne('users', conditions, (err, docs) => {
      if(!err && docs){
        if (docs.state === 0) {
          reject(0)
        }
        if(docs.password === password){
          resolve(docs);
        } else {
          reject(docs);
        }
      } else {
        reject(1);
      }
    });
  });
}

function ccLogin(req){
  console.log('cclogin');
  return new Promise((resolve, reject) => {
    smartUtil.login(req.body).then((res) => {
      console.log(res)
      if (res.data.code === 0) {
        resolve(res.data.body);
      } else {
        reject(new Error(res.data.message))
      }
    }).catch((err) => {
      console.log('cclogin' + err)
      reject(err)
    })
  });
}

/**
 * 保存用户
 */
function saveOrUpdateUser(user, req) {
  let condition = {
    loginName: user.loginName
  }
  return new Promise((resolve, reject) => {
    MongoDB.updateData('users', condition, user, (err, docs) => {
      if(!err){
        MongoDB.findOne('users', condition, (err, data) => {
          resolve(data);
        })
      } else {
        reject(err);
      }
    });
  });
}

/**
 * @getClientIP
 * @desc 获取用户 ip 地址
 * @param {Object} req - 请求
 */
function getClientIP(req) {
  return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
      req.connection.remoteAddress || // 判断 connection 的远程 IP
      req.socket.remoteAddress || // 判断后端的 socket 的 IP
      req.connection.socket.remoteAddress;
};

function getParamter(req, key) {
  let params = req.body;
  return params[key]
}

module.exports = router;
